package com.wmlive.hhvideo.heihei.login;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.heihei.beans.login.MobileLoginResponse;
import com.wmlive.hhvideo.heihei.beans.login.UserInfo;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.preferences.SPUtils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 账号管理类
 * Created by vhawk on 2017/5/23.
 */

public class AccountUtil {
    private static final String KEY_ACCOUNT_DATA = "ACCOUNT_DATA";
    private static MobileLoginResponse loginResponse = null;
    private static String token;
    private static long userId;

    private static final String KEY_TOKEN = "dc_token";  //token的key
    private static final String KEY_USER_ID = "dc_user_id";    //userId的key

    private static boolean hasLoadToken;//是否从本地加载过token

    /**
     * 保存用户登录结果
     * 注意：调用了这个方法后一定需要在io线程中调用{@link #updateUserInfo(MobileLoginResponse)}方法更新本地存储的账号信息
     *
     * @param mobileLoginResponse
     */
    public synchronized static void resetAccount(MobileLoginResponse mobileLoginResponse) {
        if (mobileLoginResponse != null) {
            loginResponse = mobileLoginResponse;
            token = loginResponse.getToken();
            userId = loginResponse.getUserInfo() != null ? loginResponse.getUserInfo().getId() : 0;
        }
    }

    /**
     * 保存token和userId到本地
     *
     * @param token
     */
    public synchronized static void saveTokenAndUserId(final String token, final long userId) {
        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, Integer>() {
                    @Override
                    public Integer apply(Integer integer) throws Exception {
                        Map<String, Object> map = new HashMap<>();
                        map.put(KEY_TOKEN, TextUtils.isEmpty(token) ? "null" : token);
                        map.put(KEY_USER_ID, userId);
                        SPUtils.putMultiParmas(DCApplication.getDCApp(), map);
                        KLog.i("====保存到本地token:" + token + " _userId:" + userId);
                        return 1;
                    }
                })
                .subscribe();

    }

    /**
     * 从本地获取token
     *
     * @return
     */
    public static String parseToken() {
        String t = SPUtils.getString(DCApplication.getDCApp(), KEY_TOKEN, "null");
        token = t;
        KLog.i("=====从本地获取token:" + t);
        return t;
    }

    /**
     * 从本地获取token
     *
     * @return
     */
    public static long parseUserId() {
        long t = SPUtils.getLong(DCApplication.getDCApp(), KEY_USER_ID, 0);
        userId = t;
        KLog.i("=====从本地获取userId:" + t);
        return t;
    }


    /**
     * 获取存储 token
     *
     * @return 本地有token 则原样返回 否则返回 null
     */
    public static String getToken() {
        if (!TextUtils.isEmpty(token) && !"null".equals(token)) {
            KLog.i("====返回内存token:" + token);
            return token;
        }
        if (!hasLoadToken) {//如果没有从本地加载过token
            KLog.i("=======获取本地token和userId1");
            String t = parseToken();
            parseUserId();
            KLog.i("=======获取本地token和userId2");
            if (TextUtils.isEmpty(t) || "null".equals(t)) {
                KLog.i("====返回本地token为空:" + t);
                return null;
            }
            KLog.i("====返回本地token:" + t);
            token = t;
            hasLoadToken = true;
        }
        return token;
//        return getAccount() == null ? "" : getAccount().getToken();
    }

    /**
     * 获取userId
     *
     * @return
     */
    public static long getUserId() {
        return userId;
//        return getAccount() == null ? -1 : (getAccount().getUserInfo() == null ? -1 : getAccount().getUserInfo().getId());
    }

    /**
     * 清除账号信息
     */
    public synchronized static void clearAccount() {
        loginResponse = null;
        token = null;
        userId = 0;
        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, Integer>() {
                    @Override
                    public Integer apply(Integer integer) throws Exception {
                        SPUtils.putString(DCApplication.getDCApp(), KEY_ACCOUNT_DATA, "");
                        saveTokenAndUserId(null, 0);
                        return 1;
                    }
                })
                .subscribe();
    }

    /**
     * 从本地文件初始化用户信息
     */
    public static void initUserInfo() {
        KLog.i("获取本地账号信息");
        try {
            loginResponse = JSON.parseObject(SPUtils.getString(DCApplication.getDCApp(), KEY_ACCOUNT_DATA, ""), MobileLoginResponse.class);
            if (loginResponse != null) {
                token = loginResponse.getToken();
                userId = loginResponse.getUserInfo() != null ? loginResponse.getUserInfo().getId() : 0;
            }
            KLog.i("初始化后的账号信息：" + (loginResponse == null ? "null" : loginResponse.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新本地账号信息
     */
    public static synchronized void updateUserInfo(MobileLoginResponse mobileLoginResponse) {
        if (mobileLoginResponse != null) {
            String info = JSON.toJSONString(mobileLoginResponse);
            KLog.i("======updateUserInfo:" + info);
            SPUtils.putString(DCApplication.getDCApp(), KEY_ACCOUNT_DATA, info);
            saveTokenAndUserId(mobileLoginResponse.getToken(), mobileLoginResponse.getUserInfo() != null ? mobileLoginResponse.getUserInfo().getId() : 0);
            KLog.i("更新本地账号信息完成");
        }
    }

    /**
     * 获取
     *
     * @return
     */
    public synchronized static MobileLoginResponse getAccount() {
        if (null == loginResponse) {
            initUserInfo();
        }
        return loginResponse;
    }

    /**
     * 是否已登录
     *
     * @return
     */
    public static boolean isLogin() {
        return !TextUtils.isEmpty(getToken()) && getUserId() > 0;
    }


    /**
     * 获取当前用户信息
     *
     * @return
     */
    public static UserInfo getUserInfo() {
        return getAccount() == null ? null : getAccount().getUserInfo();
    }

    /**
     * 更新用户信息
     *
     * @param newUserInfo
     * @return
     */
    public synchronized static void updateUserInfo(UserInfo newUserInfo) {
        if (newUserInfo != null) {
            final MobileLoginResponse bean = new MobileLoginResponse();
            bean.setUserInfo(newUserInfo);
            bean.setToken(AccountUtil.getToken());
            resetAccount(bean);
            Observable.just(1)
                    .subscribeOn(Schedulers.io())
                    .map(new Function<Integer, Boolean>() {
                        @Override
                        public Boolean apply(Integer integer) throws Exception {
                            updateUserInfo(bean);
                            return true;
                        }
                    })
                    .subscribe();
        }
    }

    /**
     * 获取 是否有管理作品的权限
     *
     * @return
     */
    public static boolean isAuthUser() {
        if (null != loginResponse) {
            return loginResponse.getUserInfo() != null && loginResponse.getUserInfo().getIs_auth_user();
        }
        return false;
    }
}
